package com.wyl.selenium.config.converter;

import cn.hutool.json.JSONUtil;
import com.wyl.selenium.annotation.FieldTypeFactory;
import com.wyl.selenium.common.CommonPage;
import com.wyl.selenium.common.ResponseData;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2023/11/17 17:26
 */
public class CustomHttpMessageConverter extends AbstractHttpMessageConverter<ResponseData> {

    public CustomHttpMessageConverter(){
        super(MediaType.APPLICATION_JSON,MediaType.APPLICATION_FORM_URLENCODED);
    }
    @Override
    protected boolean supports(Class<?> clazz) {
        return ResponseData.class.isAssignableFrom(clazz);
    }

    @Override
    protected ResponseData readInternal(Class<? extends ResponseData> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(ResponseData responseData, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        OutputStream out = outputMessage.getBody();
        Object data = responseData.getData();
        if(data instanceof CommonPage) {
            CommonPage commonPage = (CommonPage) data;
            List list = (List)commonPage.getList();
            for (Object o : list) {
                FieldTypeFactory.convert(o);
            }
        }

        out.write(JSONUtil.toJsonStr(responseData).getBytes());
    }
}
